package com.ufida.ids.util.upload;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ufida.ids.util.StringUtil;

public class UpLoad {
	private HttpServletRequest request=null;
	private String path="";//存储路径，最后不能跟路径:\\
	private int saveblock=2*1024*1024;//设置上传块的限制，即超过此数才往磁盘里写
	private int maxsize=100*1024*1024;//设置文件大小，若同时上传多个文件，必须所有上传的文件都符合这个要求
	private DiskFileItemFactory factory=null;
	private ServletFileUpload upload=null;
	private String[] truefname=null;//与form表单对应的，真正存放的文件名数组，一般不需要跟后缀名，跟了以后缀名为准

	public UpLoad(HttpServletRequest request){
	   this.request=request;
	   //上传路径
	   this.path = request.getRealPath("/upload/photo");
	   factory = new DiskFileItemFactory();
	   factory.setRepository(new File(path));
	   // 设置上传块的限制
	   factory.setSizeThreshold(saveblock);
	   // 设置一个上传对象
	   upload = new ServletFileUpload(factory);
	   //设置文件大小
	   upload.setSizeMax(maxsize);
	}
	
	public String getUpFile(Map paraValueM){
		String trueFileName = "";
		try {
			List list = upload.parseRequest(request);
			Iterator iter = list.iterator();
			// 遍历所有的表单项
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {//是上传文件项
					String uuid = UUID.randomUUID().toString().toUpperCase();
					String value = item.getName();
					if(!value.trim().equals("")){//选中文件后才执行相关操作
						int start = value.lastIndexOf("\\");
						String filename = value.substring(start + 1);
						start = filename.lastIndexOf(".");
						String postFix = filename.substring(start);
						trueFileName = uuid+postFix;
						item.write(new File(path, trueFileName));
					}
				}else{
					System.out.println(item.getFieldName());
					paraValueM.put(item.getFieldName(), StringUtil.tranStr(item.getString()));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return trueFileName;
	}

	public String getPath() {
	   return path;
	}

	public void setPath(String path) {
	   this.path = path;
	   //最后不能跟\
	   int start = path.lastIndexOf("\\");
	   if(start==path.length()-1){
	    this.path=path.substring(0, path.length()-1);
	   }
	}

	public int getSaveblock() {
	   return saveblock;
	}

	public void setSaveblock(int saveblock) {
	   this.saveblock = saveblock;
	}

	public int getMaxsize() {
	   return maxsize;
	}

	public void setMaxsize(int maxsize) {
	   this.maxsize = maxsize;
	}

	public void setTruefname(String[] truefname) {
	   this.truefname = truefname;
	}

	}


